package cn.zwx.learn.basic.redis_lock;

import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @projectName:java-basic
 * @see:cn.zwx.learn.basic.redis_lock
 * @author:zhangwenxue
 * @createTime:2021/3/24 12:10
 * @version:1.0
 */
@RestController
public class MyRedisLockTest {

    @Autowired
    private MyRedisLock myLock;

    @RequestMapping("/lock")
    public String testLock() {
        String key = "lock"+ ThreadLocalRandom.current().nextInt(0,10);
        //唯一标识，释放锁时确保是自己持有的锁
        String value = UUID.randomUUID().toString();
        Long lockTime = 10L;
        boolean lock_state = myLock.getLock(key, value, lockTime, TimeUnit.SECONDS);
        if (!lock_state){
            return "正在处理中请稍后重试...";
        }
        try {
                System.out.println("---locked---");
                //模拟服务重入过程
                if (myLock.getLock(key,value,lockTime,TimeUnit.SECONDS)) {
                    System.out.println("---relocked---");
                    myLock.release(key,value);
                }
                // 模拟业务阻塞
                TimeUnit.SECONDS.sleep(25);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            myLock.release(key,value);
        }

        return "处理成功...";
    }

}
